#include "tcpserver.h"

TCPServer::TCPServer(QObject *parent) : QObject(parent)
{
    m_tcpserver = new QTcpServer();
}

///
/// \brief 开启监听
/// \param ip
/// \param port
/// \return
///
bool TCPServer::StartListening(QString ip, quint16 port)
{
    try
    {
        if (m_tcpserver == nullptr)
        {
            m_tcpserver = new QTcpServer(this);
        }
        if (ip.isEmpty())
        {
            m_tcpserver->listen(QHostAddress::Any, port);
        }
        else
        {
            m_tcpserver->listen(QHostAddress(ip), port);
        }

        connect(m_tcpserver, &QTcpServer::newConnection,
                [=]()
        {
            NewConnection();
        });
        //qDebug() << "server address:" << m_tcpserver->serverAddress().toString();
    }
    catch (...)
    {
        m_tcpserver = new QTcpServer(this);
        return false;
    }

    return true;
}

///
/// \brief TCP Server 正在监听的地址
/// \return
///
QString TCPServer::ServerAddress()
{
    return m_tcpserver->serverAddress().toString();
}

///
/// \brief TCP Server 正在监听的端口
/// \return
///
quint16 TCPServer::ServerPort()
{
    return m_tcpserver->serverPort();
}

///
/// \brief 关闭监听
///
void TCPServer::StopListening()
{
    m_tcpserver->close();
    //m_tcpsockets.clear();
    m_tcpserver = new QTcpServer(this);
}

void TCPServer::NewConnection()
{
    m_tcpsocket = m_tcpserver->nextPendingConnection();
    //m_tcpsocket = m_tcpserver->nextPendingConnection();
    //qDebug() << "tcpsocket add address:" << m_tcpsocket;
    int socketnum = -1;
    for (int i = 0; i < m_tcpsockets.length(); i++)
    {
        if (m_tcpsockets[i] == nullptr)
        {
            //m_tcpsockets[i].data() = m_tcpserver->nextPendingConnection();
            m_tcpsockets[i] = m_tcpsocket;
            socketnum = i;
            break;
        }
    }
    if (socketnum == -1)
    {
        m_tcpsockets.append(m_tcpsocket);
        socketnum = m_tcpsockets.length() - 1;
    }
    //qDebug() << "socketnum:" << socketnum << ", length:" << m_tcpsockets.length();
    QString ip = m_tcpsockets[socketnum]->peerAddress().toString();
    quint16 port = m_tcpsockets[socketnum]->peerPort();
    // 读取数据
    connect(m_tcpsockets[socketnum], &QTcpSocket::readyRead,
            [=]()
    {
        SocketRead(m_tcpsockets[socketnum]);
    });
    connect(m_tcpsockets[socketnum], &QTcpSocket::disconnected,
            [=]()
    {
        m_tcpsockets[socketnum]->disconnect();
        emit DisConnectionSignal(ip, port);   // 发送断开连接信息
        m_tcpsockets[socketnum]->deleteLater();
        m_tcpsockets[socketnum] = nullptr;
    });
    //qDebug() << "ip:" << ip << ", port:" << port << ", name:" << m_tcpsockets[socketnum]->peerName();
    emit NewConnectingSignal(ip, port);  // 发送新的连接信息
}

///
/// \brief 读取来自客户端的数据
/// \param tcpsocket
///
void TCPServer::SocketRead(QTcpSocket *tcpsocket)
{
    QByteArray readdata = tcpsocket->readAll();
    emit ReadDataSignal(tcpsocket->peerAddress().toString(), tcpsocket->peerPort(), readdata);
}

void TCPServer::DisConnectALLClients()
{
    for (int i = 0; i < m_tcpsockets.count(); i++)
    {
        if (m_tcpsockets[i] != nullptr)
        {
            m_tcpsockets[i]->disconnectFromHost();
        }
    }
    m_tcpsockets.clear();
}

///
/// \brief 发送信息
/// \param ip
/// \param port
/// \param senddata
/// \return
///
bool TCPServer::SendData(QString ip, quint16 port, const QByteArray senddata)
{
    for (int i = 0; i < m_tcpsockets.count(); i++)
    {
        //qDebug() << "i:" << i << ", address:" << m_tcpsockets[i]->peerAddress().toString() << ", port:" << m_tcpsockets[i]->peerPort();
        if (ip != "ALL Connections")
        {
            if (m_tcpsockets[i] != nullptr && (m_tcpsockets[i]->peerAddress().toString() == ip || m_tcpsockets[i]->peerAddress().toString() == "::ffff:" + ip) && m_tcpsockets[i]->peerPort() == port)
            {
                //qDebug() << "write is OK";
                m_tcpsockets[i]->write(senddata);
                return true;
            }
        }
        else
        {
            m_tcpsockets[i]->write(senddata);
        }
    }
    return true;
}

///
/// \brief 判断是否在监听状态
/// \return
///
bool TCPServer::isListening()
{
    return m_tcpserver->isListening();
}
